package com.example.activitysys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.activitysys.entity.LostItem;
import com.example.activitysys.service.LostItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 失物招领管理控制器
 */
@Controller
@RequestMapping("/lost-item")
public class LostItemController {

    @Autowired
    private LostItemService lostItemService;

    /**
     * 失物列表页面
     */
    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String title,
                       @RequestParam(required = false) String category,
                       @RequestParam(required = false) String location,
                       Model model,
                       HttpSession session) {
        // 检查登录状态
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }

        // 构建查询条件
        QueryWrapper<LostItem> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0); // 只查询未删除的记录
        
        if (StringUtils.hasText(title)) {
            wrapper.like("title", title);
        }
        if (StringUtils.hasText(category)) {
            wrapper.eq("category", category);
        }
        if (StringUtils.hasText(location)) {
            wrapper.like("location", location);
        }
        
        // 按提交时间倒序排列
        wrapper.orderByDesc("submit_time");

        // 分页查询
        IPage<LostItem> page = lostItemService.page(new Page<>(pageNum, pageSize), wrapper);
        
        model.addAttribute("page", page);
        model.addAttribute("title", title);
        model.addAttribute("category", category);
        model.addAttribute("location", location);
        
        return "lost-item/list";
    }

    /**
     * 新增失物页面
     */
    @GetMapping("/add")
    public String add(HttpSession session) {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        return "lost-item/add";
    }

    /**
     * 保存失物
     */
    @PostMapping("/save")
    public String save(LostItem lostItem, 
                      @RequestParam("imageFile") MultipartFile imageFile,
                      HttpSession session) throws IOException {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        
        // 处理文件上传
        if (imageFile != null && !imageFile.isEmpty()) {
            // 获取项目根目录下的upload目录
            String projectPath = System.getProperty("user.dir");
            String uploadDir = Paths.get(projectPath, "upload").toAbsolutePath().toString();
            Path uploadPath = Paths.get(uploadDir);
            
            // 确保上传目录存在
            Files.createDirectories(uploadPath);
            
            // 生成唯一文件名
            String originalFilename = imageFile.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + fileExtension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(filename);
            Files.write(filePath, imageFile.getBytes());
            
            // 设置图片URL
            lostItem.setImageUrl("/upload/" + filename);
        }
        
        // 设置默认状态为未认领
        lostItem.setStatus(0);
        
        lostItemService.save(lostItem);
        return "redirect:/lost-item/list";
    }

    /**
     * 编辑失物页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model, HttpSession session) {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        
        LostItem lostItem = lostItemService.getById(id);
        model.addAttribute("lostItem", lostItem);
        return "lost-item/edit";
    }

    /**
     * 更新失物
     */
    @PostMapping("/update")
    public String update(LostItem lostItem,
                        @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
                        HttpSession session) throws IOException {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        
        // 处理文件上传（如果提供了新文件）
        if (imageFile != null && !imageFile.isEmpty()) {
            // 获取项目根目录下的upload目录
            String projectPath = System.getProperty("user.dir");
            String uploadDir = Paths.get(projectPath, "upload").toAbsolutePath().toString();
            Path uploadPath = Paths.get(uploadDir);
            
            // 确保上传目录存在
            Files.createDirectories(uploadPath);
            
            // 生成唯一文件名
            String originalFilename = imageFile.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + fileExtension;
            
            // 保存文件
            Path filePath = uploadPath.resolve(filename);
            Files.write(filePath, imageFile.getBytes());
            
            // 设置图片URL
            lostItem.setImageUrl("/upload/" + filename);
        }
        lostItemService.updateById(lostItem);
        return "redirect:/lost-item/list";
    }

    /**
     * 删除失物（逻辑删除）
     */
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Long id, HttpSession session) {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        
        lostItemService.removeById(id);
        return "redirect:/lost-item/list";
    }

    /**
     * 查看失物详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, Model model, HttpSession session) {
        if (session.getAttribute("admin") == null) {
            return "redirect:/login";
        }
        
        LostItem lostItem = lostItemService.getById(id);
        model.addAttribute("lostItem", lostItem);
        return "lost-item/detail";
    }
}